﻿using Ags.MonsterTools.Common;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ags.MonsterTools
{
    public class ViewManagerImpl : IViewManager
    {
        private readonly IRegionManager _rm;
        private readonly IUnityContainer _container;
        
        public ViewManagerImpl(IRegionManager rm, IUnityContainer container)
        {
            _rm = rm;
            _container = container;
        }

        public void NavigateToView(Type viewType, string regionName, string viewName, Dictionary<string, object> parameters)
        {
            object view = null;
            if (parameters == null || !parameters.Any())
            {
                view = _container.Resolve(viewType, viewName);
            }
            else
            {
                ResolverOverride[] po = parameters.Select(p => new ParameterOverride(p.Key, p.Value) as ResolverOverride).ToArray();
                view = _container.Resolve(viewType, viewName, po);
            }
            if(view == null)
                throw new InvalidOperationException("Could not resolve view");

            if (_rm.Regions[regionName].Views.Contains(view))
            {
                _rm.Regions[regionName].Activate(view);
            }
            else
            {
                _rm.RegisterViewWithRegion(regionName, () => view); 
                _rm.Regions[regionName].Activate(view);
            }
        }

        public void RemoveView(object view, string regionName)
        {
            _rm.Regions[regionName].Remove(view);
            
            var registration = _container.Registrations.FirstOrDefault(r => r.RegisteredType == view.GetType());
            if(registration == null)
                return;
            if (registration.LifetimeManagerType == typeof (TransientLifetimeManager))
            {
                var viewObj = view as IView;
                if (viewObj != null) viewObj.Dispose();   
            }
        }
    }
}
